<?php
/**
 * @name 直播用户后台管理控制器
 * @namespace app\admin\controller;
 * @use app\common\controller\AdminBase;
 * @date 2016-8-31
 * @author zhibo
 */
namespace app\admin\controller;
use app\common\controller\AdminBase;
class Stream extends AdminBase {
    protected function _initialize(){
        parent::_initialize();
        $this->mod = model('stream/Stream');
    }
    /**
     * @name 直播间列表
     */
    public function index(){
        $this->pageTitle = '直播间列表';
        //统一配置
        $this->setConfig();
        //条件
        $this->location && $map['location'] = ['like', '%' . string_filter($this->location) . '%'];
        $this->stream_title && $map['stream_title'] = ['like', '%' . string_filter($this->stream_title) . '%'];
        $this->uname && $map['uname'] = ['like', '%' . string_filter($this->uname) . '%'];
        $this->sex && $map['sex'] = (int)$this->sex;
        if($this->status && (int)$this->status - 1 >= 0)$map['status'] = (int)$this->status - 1;
        $list =  $this->mod->adminGetList($map,"FIELD(status,1,2,0),locate('" . $this->stream_title. "', stream_title) ASC,length(stream_title)-length('" . $this->stream_title . "'),airtime desc",14);
        $this->assign('list',$list);
        return $this->fetch();
    }
    protected function setConfig(){
        $config = [
            'searchKey' =>  [
                'location' => [
                    'type'  => 'input',//输入框类型
                    'value_default' => $this->location,//默认值
                    'name'  => '地区',//名称
                    'info'  => '输入地区进行筛选',//提示文字
                    'text_max' => 5,//允许的最长字数
                ],
                'sex'   =>  [
                    'type'  => 'radio',//单选
                    'value' => [
                        0 => '全部',
                        1 => '男',
                        2 => '女',
                    ],//所有的选项,key=>value
                    'value_default' => intval($this->sex) ?:0, //默认选中项的key
                    'name'  => '性别',//名称
                ],
                'stream_title' => [
                    'type'  => 'input',
                    'value_default' => $this->stream_title,
                    'name'  => '直播间标题',
                    'info'  => '输入直播间标题搜索'
                ],
                'uname' => [
                    'type'  => 'input',
                    'value_default' => $this->uname,
                    'name'  => '用户名',
                    'info'  => '输入用户名搜索'
                ],
                'status'   =>  [
                    'type'  => 'radio',//下拉列表
                    'value' => [0 => '全部',1 =>'已禁播',2=>'正在直播',3=>'未开播',],//可选项
                    'value_default' => (int)$this->status ?:0,//默认选择key
                    'name'  => '直播间状态',//名称
                ]
            ],
            'searchPostUrl' => U('admin/Stream/index'),//搜索提交的地址
            'openBox'  => isset($this->data['stream_title']) ? true : false,//是否默认打开搜索框
        
        ];
        $this->searchConfig($config);
    }
    /**
     * @name 直播间详情
     */
    public function info(){
        $this->pageTitle = '直播间详情';
        $this->stream_uid = decrypt_id($this->stream_uid);
        if($this->dis == 'video'){
            //获取回放视频
            $map['uid'] = $this->stream_uid;
            $video_list = model('stream/Video')->getList($map);
            $video_list['data'] = object2array($video_list['data']);
            $this->assign('video_list',$video_list);
            $this->assign('dis',$this->dis);
            $userAccount = model('open/UserData')->getUserAccount($this->stream_uid);
            $this->assign('user_account',$userAccount);
        }
        //检测禁播情况
        $this->mod->getDisable($this->stream_uid);
        $info =  $this->mod->adminGetInfo(['uid'=>$this->stream_uid]);
        $this->assign('info',$info);
        //获取当前管理员的im账号
        $aid = decrypt_id(session('aid'));
        $imUser = model('open/UserImAccount')->getImUser($aid,true,true);
        if($imUser){
            $this->assign('im_token',$imUser['im_pwd']);
        }
        return $this->fetch('stream_info');
    }
    /**
     * @name 获取直播间的实时统计
     */
    public function getTmpeAccount(){
        if(IS_AJAX){
            $this->stream_uid = decrypt_id($this->stream_uid);
            $temp = $this->mod->getTmpeAccount($this->stream_uid);
            if($temp){
                return ['status' =>1,'data'=>['info'=>'ok','account'=>$temp]];
            }
        }
        return ['status' =>0,'message'=>'This account not find'];
    }
    /**
     * @name 编辑直播间公共
     */
    public function edit_notice(){
        if(!IS_POST){
            $this->pageTitle = '编辑直播间公告';
            $model = model('admin/Config');
            $list = $model->getConfigList('stream_notice');
            if(!empty($list['data'])){
                $this->assign('info',$list['data'][0]);
            }else{
                $data = [
                    'value' => ['text' => ''],
                    'type'  => 'stream_notice',
                    'key'   => 'stream_notice',
                    'description' => '直播间公告'
                ];
                $config_id = $model->addConfig($data,2);
                $this->assign('info',['config_id'=>$config_id,'status'=>1]);
            }
            return $this->fetch('notice');
        }
        $res = false;
        if(IS_AJAX){
            $this->config_id = decrypt_id($this->config_id);
            $this->notice = string_filter($this->notice);
            if(get_str_length($this->notice) > 100){
                return ['status'=>0,'message'=>'公告内容不得超过100个汉字'];
            }
            if($this->config_id){
                $data = [
                    'config_id' => $this->config_id,
                    'value' => ['text' => $this->notice],
                    'status' => $this->status
                ];
                $res = model('admin/Config')->editConfig($data,2);
            }
        }
        if($res){
            return ['status'=>1,'data'=>['info'=>'保存成功','jumpurl'=>U('admin/Stream/edit_notice')]];
        }
        return ['status'=>0,'message'=>'保存失败,请重新尝试'];
    }
    /**
     * @name 视频回放配置
     */
    public function video_config(){
        if(!IS_POST){
            $this->pageTitle = '回放视频配置';
            $model = model('admin/Config');
            $list = $model->getConfigList('video','video_config');
            if(!empty($list['data'])){
                $this->assign('info',$list['data'][0]);
            }else{
                $data = [
                    'value' => [
                        'video_prefix'         =>'zb_',//保存的视频前缀
                        'video_suffix'         =>'mp4',//保存的视频后缀,根据后缀名称进行转码
                        'video_effective_time' => 30,//保存的视频有效时间,单位为秒,0表示每次直播都保存
                        'video_title'          => '[uname]的视频',//设置视频的标题  [uname]会替换成用户昵称
                    ],
                    'type'  => 'video',
                    'key'   => 'video_config',
                    'description' => '回放视频配置'
                ];
                $config_id = $model->addConfig($data,2);
                $this->assign('info',['config_id'=>$config_id,'status'=>1]);
            }
            return $this->fetch('video_config');
        }
        $res = false;
        if(IS_AJAX){
            $this->config_id = decrypt_id($this->config_id);
            $model = model('admin/Config');
            $value = [
                'video_effective_time' => (int)$this->time,
                'video_title'          => string_filter($this->video_title),
            ];
            if($this->config_id){
                $list = $model->getConfigById($this->config_id);
                $data = [
                    'config_id' => $this->config_id,
                    'value' => array_merge($list['value'],$value),
                    'status' => $this->status
                ];
                $res = $model->editConfig($data,2);
            }
        }
        if($res){
            return ['status'=>1,'data'=>['info'=>'保存成功','jumpurl'=>U('admin/Stream/video_config')]];
        }
        return ['status'=>0,'message'=>'保存失败,请重新尝试'];
    }
    /**
     * @name 直播配置
     */
    public function stream_config(){
        if(!IS_POST){
            $this->pageTitle = '直播间配置';
            $model = model('admin/Config');
            $list = $model->getConfigList('stream','stream_config');
            if(!empty($list['data'])){
                $this->assign('config',$list['data'][0]);
            }else{
                $data = [
                    'value' => [
                        'stream_title' => '',
                        'stream_icon'  => 0,
                        'stream_snapshot' => 1
                    ],
                    'type'  => 'stream',
                    'key'   => 'stream_config',
                    'description' => '直播间配置'
                ];
                $config_id = $model->addConfig($data,2);
                $this->assign('config',['config_id'=>$config_id,'value'=>$data['value']]);
            }
            return $this->fetch('stream_config');
        }
        $res = false;
        if(IS_AJAX){
            $this->config_id = decrypt_id($this->config_id);
            $model = model('admin/Config');
            $this->stream_title = string_filter($this->stream_title);
            if(get_str_length(str_replace('[uname]','',$this->stream_title)) > 7){
                return ['status'=>0,'message'=>'直播间自定义标题不能超过7个汉字'];
            }
            $value = [
                'stream_snapshot' => (int)$this->stream_snapshot,
                'stream_title'    => msubstr(string_filter($this->stream_title),0,14)
            ];
            $icon = decrypt_id($this->stream_icon);
            $icon && $value['stream_icon'] = $icon;
            if($this->config_id){
                $list = $model->getConfigById($this->config_id);
                $data = [
                    'config_id' => $this->config_id,
                    'value' => array_merge($list['value'],$value),
                ];
                $res = $model->editConfig($data,2);
            }
        }
        if($res){
            return ['status'=>1,'data'=>['info'=>'保存成功','jumpurl'=>U('admin/Stream/stream_config')]];
        }
        return ['status'=>0,'message'=>'保存失败,请重新尝试'];
    }
    /**
     * @name 删除上传的直播封面默认图片
     */
    public function rm_upload_image(){
        if(IS_AJAX){
            if(true !== $this->checkData(['attach_id'])){
                return ['status'=>0,'message'=>$this->error_info];
            }
            model('attach/Attach')->deleteAttachById($this->attach_id);
            exit;
        }
    }
    
    /**
     * @name 设置禁播状态
     */
    public function setDisable(){
        if(IS_AJAX){
            $this->stream_uid = decrypt_id($this->stream_uid);
            if($this->stream_uid){
                //获取直播间状
                $status = $this->mod->getStreamStatus($this->stream_uid);
                $uname = getUname($this->stream_uid);
                if($this->disable_code == 0){
                    //永久禁播
                    if($status == 0){
                        return ['status'=>1,'data'=>['info'=>'该直播间已禁播']];
                    }
                    //请求设置禁播
                    $stream = A('stream/Stream')->getStreamClass($this->stream_uid);
                    $this->mod->update(['status' => 0,'disable_time'=>0], ['uid' => $this->stream_uid]);
                    //记录日志
                    system_log('将'.$uname.'的直播间永久禁播','admin_stream',['key'=>'user_stream']);
                    $this->sendEndStream($this->stream_uid,$stream->id,'已被禁止直播');
                    $stream->disable();
                }elseif($this->disable_code == 2){
                    //限时禁播,请求设置禁播
                    $stream = A('stream/Stream')->getStreamClass($this->stream_uid);
                    if(!$this->disable_time || !$this->disable_unit){
                        return ['status' => 0,'message' => '请输入有效时间'];
                    }
                    $time = $this->getDisableTime($this->disable_time,$this->disable_unit);
                    if($time === false){
                        return ['status' => 0,'message' => '你输入的时间过长,请设置永久禁播'];
                    }
                    $stream->disable($time);
                    $this->mod->update(['status' => 0,'disable_time'=>$time], ['uid' => $this->stream_uid]);
                    //记录日志
                    system_log('将'.$uname.'的直播间禁播到:'.date('Y-m-d H:i',$time),'admin_stream',['key'=>'user_stream']);
                    $this->sendEndStream($this->stream_uid,$stream->id,'已被禁止直播');
                }elseif($this->disable_code == 1){
                    //直播间存在,检验直播间信息
            		if ($status === 0) {
            			//已经被禁播,解禁播,更新流信息
                        $stream = A('stream/Stream')->getStreamClass($this->stream_uid);
        				$stream->enable();
                        $this->mod->update(['status' => 2,'disable_time'=>0], ['uid' => $this->stream_uid]);
                        //日志
                        system_log('将'.$uname.'的直播间解除禁播状态','admin_stream',['key'=>'user_stream']);
            		}
                }else{
                    return ['status'=>0,'message'=>'设置失败,请稍后重试'];
                }
                //清理缓存
                cleanData($this->stream_uid,'stream');
                $data = [];
                $data['info'] = '设置成功';
                $time && $data['time'] = date('Y-m-d H:i',$time);
                return ['status'=>1,'data'=>$data];
            }
        }
        return ['status'=>0,'message'=>'设置失败,请稍后重试'];
    }
    /**
     * @name 计算禁播时间
     */
    protected function getDisableTime($time = 0,$unit = 0){
        try{
            switch($unit){
                case 'i':
                    $time = strtotime('+'.$time.' minute');
                    break;
                case 'h':
                    $time = strtotime('+'.$time.' hour');
                    break;
                case 'd':
                    $time = strtotime('+'.$time.' day');
                    break;
                case 'm':
                    $time = strtotime('+'.$time.' month ');
                    break;
                case 'y':
                    $time = strtotime('+'.$time.' year ');
                    break;
                default:
                    $time = NOW_TIME;
                    break;
            }
        }catch(Exception $e){
            return $e;
        }
        return $time;
    }
    /**
     * @name 聊天服务器配置
     */
    public function webim_config(){
        exit('功能未完成');
    }
    /**
     * @name 直播服务器配置
     */
    public function stream_service(){
        if(!IS_POST){
            $this->pageTitle = '直播服务器配置';
            $model = model('admin/Config');
            $list = $model->getConfigList('stream','stream_service');
            if(!empty($list['data'])){
                $this->assign('config',$list['data'][0]);
            }else{
                $data = [
                    'value' => [
                        'qiniu_accessKey'       => '',//七牛授权accesskey
                        'qiniu_secretKey'       => '',//七牛授权secretkey
                        'hub_name'              => '',//所在应用'
                        'hub_ts_url'            => '',//切片域名(回播地址)
                        'pipeline'              => '',//数据处理队列
                    ],
                    'type'  => 'stream',
                    'key'   => 'stream_service',
                    'description' => '直播服务器配置'
                ];
                $config_id = $model->addConfig($data,2);
                $this->assign('config',['config_id'=>$config_id,'value'=>$data['value']]);
            }
            return $this->fetch('stream_service');
        }
        $res = false;
        if(IS_AJAX){
            $this->config_id = decrypt_id($this->config_id);
            if($this->config_id){
                $model = model('admin/Config');
                $value = [
                    'qiniu_accessKey'    => string_filter($this->qiniu_accessKey),
                    'qiniu_secretKey'    => string_filter($this->qiniu_secretKey),
                    'hub_name'           => string_filter($this->hub_name),
                    'hub_ts_url'         => string_filter($this->hub_ts_url),
                    'pipeline'           => string_filter($this->pipeline),
                ];
                $data = [
                    'config_id' => $this->config_id,
                    'value' => $value,
                ];
                $res = $model->editConfig($data,2);
            }
        }
        if($res){
            return ['status'=>1,'data'=>['info'=>'保存成功','jumpurl'=>U('admin/Stream/stream_service')]];
        }
        return ['status'=>0,'message'=>'保存失败,请重新尝试'];
    }
    /**
     * @name webim 
     */
    public function test(){
        exit('暂时不能使用该功能');
        $data = [
            'value' => 
                [
                    'extranet' => 'ws://39.106.7.23:9900/',
                    // 'intranet' => 'ws://127.0.0.1:9902/',
             ],
            'type'  => 'im',
            'key'   => 'im_config',
            'description' => '聊天服务器1号'
        ];
        $config_id = model('admin/Config')->addConfig($data,2);
    }
    /**
     * @name 获取用户昵称
     */
    public function getStreamUserName(){
        $user_id = model('open/User')->getUidByUsid($this->usid);
        $uname = getUname($user_id);
        if($uname){
            return ['status'=>1,'data'=>['uname'=>$uname]];
        }
        return ['status'=>0,'message'=>'not find user'];
    }
    /**
     * @name 发送IM消息
     */
    public function sendMessage(){
        if(IS_AJAX){
            $msg = [
                'uid' => 0,//管理员
                'type' => 210,
                'rt'   => false,
                'txt'  => $this->txt,
                'ext'  => [
                    'customID' => 50800
                ],
                'cid' => $this->cid,
            ];
            $res = model('open/UserImAccount')->messagePOST($msg);
            if($res['code'] == 201){
                return ['status'=>1,'data'=>['info'=>'消息发送成功']];
            }
        }
        return ['status'=>0,'message'=>'消息发送失败,请重新尝试'];
    }
    /**
     * @name 发送禁播通知
     */
    protected function sendEndStream($uid = 0,$stream_id = '',$txt = ''){
        if($uid && $stream_id){
            //发送通知
            $im_model = model('open/UserImAccount');
            $im = $im_model->getConversation(['affix' => $stream_id, 'type' => 2], false);
            $msg = [
                'uid' => 0,//管理员
                'type' => 210,
                'rt'   => false,
                'txt'  => $txt,
                'ext'  => [
                    'customID' => 50700,
                    'ZBUSID' => model('open/User')->getUsidByUid($uid),
                ],
                'cid' => $im['cid'],
            ];
            $im_model->messagePOST($msg);
        }
    }
    /**
     * @name 禁言
     */
    public function setImStoMessage(){
        if(IS_AJAX){
            $map = [
				'cid' => (int) $this->im_cid,
				'uids' => $this->im_uid
			];
            $map['expire'] = $this->time == 0 ? (int)$this->time : $this->getDisableTime($this->time,$this->unit);
            $res = model('open/UserImAccount')->limitedADD($map);
			if ($res['code'] == '201') {
				return ['status' => 1, 'data' =>['info'=>'禁言成功']];
			}
        }
        return ['status'=>0,'message'=>'设置失败,请重新尝试'];
    }
	/**
     * @name 直播3G页面配置
     */
    public function stream_3gconfig(){
        if(!IS_POST){
            $this->pageTitle = '直播3G页面展示配置';
            $model = model('admin/Config');
            $list = $model->getConfigList('stream','stream_3gconfig');
            if(!empty($list['data'])){
                $this->assign('config',$list['data'][0]);
            }else{
                $data = [
                    'value' => [
                        'page_title' => '',
                        'app_logo' => '',
                        'app_desc'  => '',
                        'app_version' => '',
                        'app_down_url' => '',
                        'stream_not_start' => '直播已结束'
                    ],
                    'type'  => 'stream',
                    'key'   => 'stream_3gconfig',
                    'description' => '直播3G页面展示配置'
                ];
                $config_id = $model->addConfig($data,2);
                $this->assign('config',['config_id'=>$config_id,'value'=>$data['value']]);
            }
            return $this->fetch('stream_3gconfig');
        }
        $res = false;
        if(IS_AJAX){
            $this->config_id = decrypt_id($this->config_id);
            if($this->config_id){
                $model = model('admin/Config');
                $value = [
                    'app_logo' => decrypt_id($this->app_logo),
                    'page_title'    => string_filter($this->page_title),
                    'app_desc'  => string_filter($this->app_desc),
                    'app_version' => string_filter($this->app_version),
                    'app_down_url' => string_filter($this->app_down_url),
                    'stream_not_start' => string_filter($this->stream_not_start),
                    
                ];
                $data = [
                    'config_id' => $this->config_id,
                    'value' => $value
                ];
                $res = $model->editConfig($data,2);
            }
        }
        if($res){
            return ['status'=>1,'data'=>['info'=>'保存成功','jumpurl'=>U('admin/Stream/stream_3gconfig')]];
        }
        return ['status'=>0,'message'=>'保存失败,请重新尝试'];
    }
}
